package com.qtyx.nms.mvp.base

import android.util.Log
import android.widget.Toast
import com.qtyx.nms.MyApp.Companion.getMyAppContext
import com.qtyx.nms.mvp.model.network.ApiServer
import com.qtyx.nms.mvp.model.network.CheckNetWork
import com.qtyx.nms.mvp.model.network.RetrofitUtil
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import retrofit2.Retrofit

/**
 * 公共Presenter
 */
open class BasePresenter {

    fun getApiServer(): ApiServer {
        return RetrofitUtil.getInstance().getApiService()
    }

    private val mCompositeDisposable: CompositeDisposable = CompositeDisposable()

    /**
     * 请求数据
     */
    protected fun <bean:BaseBean> requestData(observable: Observable<bean>, observer: DisposableObserver<bean>) {
        if (!CheckNetWork.netWorkState) {
            Toast.makeText(getMyAppContext(), "没有可用的网络", Toast.LENGTH_SHORT).show()
            return
        }
        val disposable: Disposable = observable
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(observer)
        mCompositeDisposable.add(disposable)
    }

    /**
     * 解除绑定
     */
    fun detachView() {
        if (!mCompositeDisposable.isDisposed) {
            mCompositeDisposable.dispose()
        }
    }

}